import 'package:gold/base/view_model.dart';
import 'package:gold/http/api_my.dart';
import 'package:gold/http/http.dart';
import 'package:gold/model/fund_list_model.dart';
import 'package:gold/utils/xfg_extension.dart';
import 'package:pull_to_refresh_flutter3/pull_to_refresh_flutter3.dart';

/// @description:
/// @author tangzhentao
/// @created at 22:57 2024/12/14


class FundDetailsViewmodel extends Viewmodel {
  /// 数据
  final List<FundData> list = [];
  /// 刷新控制器
  final RefreshController controller = RefreshController();
  /// 收入类型
  FundType _fundType = FundType.all;

  FundType get fundType => _fundType;
  set fundType(FundType value) {
    if (_fundType != value) {
      _fundType = value;
      loadFirst();
    }
  }

  /// 页码
  int _page = 1;

  /// 加载数据
  Future loadFirst() async {
    setLoading();
    _page = 1;
    final result = await Http().request<FundListModel>(ApiMy.logsAmount, showErrorMsg: false,
        data: {'page': _page, 'mode': _fundType.type});
    if (result.success) {
      final data = _handleList(result.data?.data);
      controller.footerMode?.value = _page < (result.data?.totalPages?? 0) ? LoadStatus.canLoading:LoadStatus.noMore;
      if (data.isNotEmpty) {
        list.clear();
        list.addAll(data);
        setSuccess();
      } else {
        setEmpty(msg: '数据异常');
      }
    } else {
      setFailed(msg: result.msg);
    }
  }

  /// 刷新数据
  Future refresh() async {
    _page = 1;
    final result = await Http().request<FundListModel>(ApiMy.logsPoint, showErrorMsg: false,
        data: {'page': _page, 'mode': _fundType.type});
    if (result.success) {
      final data = _handleList(result.data?.data);
      controller.refreshCompleted();
      controller.footerMode?.value = _page < (result.data?.totalPages?? 0) ? LoadStatus.canLoading:LoadStatus.noMore;
      if (data.isNotEmpty) {
        list.clear();
        list.addAll(data);
        setSuccessChange();
      }
    } else {
      controller.refreshFailed();
    }
  }

  /// 加载更多数据
  Future loadMore() async {
    _page++;
    final result = await Http().request<FundListModel>(ApiMy.logsPoint, showErrorMsg: false,
        data: {'page': _page, 'mode': _fundType.type});
    if (result.success) {
      final data = _handleList(result.data?.data);
      controller.loadComplete();
      controller.footerMode?.value = _page < (result.data?.totalPages?? 0) ? LoadStatus.canLoading:LoadStatus.noMore;
      if (data.isNotEmpty) {
        list.addAll(data);
        setSuccessChange();
      } else {
        controller.loadNoData();
      }
    } else {
      controller.loadFailed();
    }
  }

  /// 处理列表数据
  List<FundData> _handleList(List<FundModel>? data) {
    final List<FundData> list = [];
    if (data?.isNotEmpty == true) {
      for (var fund in data!) {
        final date = DateTime.tryParse(fund.createdAt?? '');
        if (date != null) {
          if (list.isNotEmpty) {
            final yyyyMM = date.format(formats: formatYYYYMMChinese);
            bool exit = false;
            for (var fundData in list) {
              if (fundData.date == yyyyMM) {
                fund.showTime = date.format(formats: formatMMDDHHNNChinese);
                fundData.data.add(fund);
                exit = true;
                break;
              }
            }
            if (!exit) {
              fund.showTime = date.format(formats: formatMMDDHHNNChinese);
              list.add(FundData(date.format(formats: formatYYYYMMChinese), [fund]));
            }
          } else {
            fund.showTime = date.format(formats: formatMMDDHHNNChinese);
            list.add(FundData(date.format(formats: formatYYYYMMChinese), [fund]));
          }
        }
      }
    }
    return list;
  }

  /// 是否展示详情
  void changeShowDetails(int index) {
    list[index].showDetails = !list[index].showDetails;
    setSuccessChange();
  }

  @override
  onReload() => loadFirst();

  @override
  onRetry() => loadFirst();

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }
}

enum FundType {
  all(des: '全部', type: ''),
  income(des: '收入', type: 'income'),
  expend(des: '支出', type: 'expend');

  const FundType({required this.des, required this.type});
  final String des;
  final String type;
}

class FundData {
  final String date;
  bool showDetails;
  final List<FundModel> data;

  FundData(this.date, this.data, {this.showDetails = true});
}